package com.example.tangyee.utils;

import android.os.AsyncTask;
import android.util.Log;

import com.example.tangyee.bean.HealthVideo;

import org.jsoup.HttpStatusException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;

public class GetHealthVideos extends AsyncTask<Void, Void, List<HealthVideo>> {

    private static final String TAG = "GetHealthVideos";

    private int page;
    private int pageSize;


    private OnPostExecute mExecute;

    public GetHealthVideos(int page, int pageSize, OnPostExecute execute){
        this.page = page;
        this.pageSize = pageSize;
        this.mExecute = execute;
    }

    @Override
    protected List<HealthVideo> doInBackground(Void... voids) {

        if (isCancelled()) {
            return new ArrayList<>();
        }
        // 采用get的方式访问url
        List<HealthVideo> videos = new ArrayList<>();
        try {
            Document document = Jsoup.connect(ConstantsUtil.GET_HEALTH_VIDEOS).get();
            Elements lis = document.select("ul.search-result-list>li");
            for (Element li : lis) {
                HealthVideo healthVideo = new HealthVideo();

                String videoId = li.getElementsByAttribute("href").first().attr("href");
                healthVideo.setVideoId(videoId);

                String image = li.getElementsByAttribute("src").first().attr("src");
                healthVideo.setImage(image);

                String title = li.select("div.result-text>h2").text();
                healthVideo.setTitle(title);

                Elements spans = li.select("span.fl");
                String type = spans.first().text();
                healthVideo.setType(type);
                String heat = spans.next().first().text();
                healthVideo.setHeat(heat);
                videos.add(healthVideo);
            }

        } catch (SocketTimeoutException ste) {
            Log.e(TAG, "doInBackground: ", ste);
            return null;
        } catch (IOException e) {
            Log.e(TAG, "doInBackground: ", e);
            return null;
        }

        return videos;
    }

    @Override
    protected void onPostExecute(List<HealthVideo> articles) {
        mExecute.onPostExecute(articles);
    }

    public void setOnPostExecute(OnPostExecute execute) {
        this.mExecute = execute;
    }

    public interface OnPostExecute {
        void onPostExecute(List<HealthVideo> items);
    }
}
